// Copyright 2018 The QOS Authors

package handler

import (
	"io"
	"log"
	"net/http"
	"os"

	"github.com/gin-gonic/gin"
	"github.com/go-mail/mail"
)

var emailSmtpServer string
var emailUser string
var emailPassword string

func init() {
	emailSmtpServer = os.Getenv("MailSmtpServer")
	emailUser = os.Getenv("MailUser")
	emailPassword = os.Getenv("MailPassword")
}

type EmailReq struct {
	To          string `form:"to" json:"to" binding:"required"`
	Cc          string `form:"cc" json:"cc"`
	Bcc         string `form:"bcc" json:"bcc"`
	Subject     string `form:"subject" json:"subject"`
	ContentType string `form:"contentType" json:"contentType"`
	Body        string `form:"body" json:"body"`
}

type User struct {
	Address string
	Name    string
}

func EmailHander(c *gin.Context) {
	var body EmailReq
	if err := c.Bind(&body); err != nil {
		c.JSON(http.StatusBadRequest, map[string]string{"message": "请求参数错误" + err.Error()})
		return
	}

	file, err := c.FormFile("file")
	if err != nil {
		c.JSON(http.StatusInternalServerError, map[string]string{"message": "读取附件失败" + err.Error()})
		return
	}

	var att *Attach
	if file != nil {
		reader, err := file.Open()
		if err != nil {
			log.Printf("open file err:%+v", err)
			c.JSON(http.StatusInternalServerError, map[string]string{"message": "读取附件失败" + err.Error()})
			return
		}

		att = &Attach{FileName: file.Filename, Reader: reader}
	}

	if err := SendEmail(body.To, body.Cc, body.Bcc, body.Subject, body.ContentType, body.Body, att); err != nil {
		log.Printf("send mail err:%+v", err)
		c.JSON(http.StatusInternalServerError, map[string]string{"message": "发送失败" + err.Error()})
		return
	}

	c.JSON(http.StatusOK, nil)

}

type Attach struct {
	FileName string
	Reader   io.Reader
}

// SendEmail 发送邮件
func SendEmail(to, cc, bcc, subject, contentType, body string, att *Attach) error {
	m := mail.NewMessage()
	m.SetAddressHeader("From", emailUser, "QSTO")
	m.SetAddressHeader("To", to, "")
	if cc != "" {
		m.SetHeader("Cc", m.FormatAddress(cc, "")) // 抄送
	}
	if bcc != "" {
		m.SetHeader("Bcc", m.FormatAddress(bcc, "")) // 暗送
	}
	m.SetHeader("Subject", subject)
	m.SetBody(contentType, body)

	if att != nil {
		m.AttachReader(att.FileName, att.Reader) // 附件
	}

	d := mail.NewDialer(emailSmtpServer, 465, emailUser, emailPassword)
	if err := d.DialAndSend(m); err != nil {
		return err
	}

	return nil
}
